<script setup lang="jsx">
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useFs } from '@fast-crud/fast-crud'
import { useRouter } from 'vue-router'
import http from '@/http'
import { get } from 'lodash-es'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'

const router = useRouter()
const syncModalOpen = ref(false)
const syncFormData = ref({
  ak: '',
  sk: ''
})
//此处为crudOptions配置
const createCrudOptions = function () {
  return {
    crudOptions: {
      actionbar: {
        buttons: {
          add: {
            click() {
              return router.push({
                path: `/create`
              })
            }
          },
          syncTask: {
            text: '手动同步任务状态',
            click() {
              syncFormData.value = {}
              syncModalOpen.value = true
            }
          }
        }
      },
      request: {
        async pageRequest(query) {
          return http.post('/task/find_example', query)
        },
        addRequest() {},
        editRequest() {},
        delRequest() {}
      },
      table: {},
      search: {
        options: {
          labelCol: {
            span: 8
          }
        },
        container: {
          col: { span: 6 }
        }
      },
      columns: {
        id: {
          title: '任务ID',
          type: 'text',
          column: {
            align: 'center',
            width: 100
          }
        },
        sid: {
          title: '服务器ID',
          type: 'text',
          column: {
            formatter({ row }) {
              return get(row, 'order.server.id', '-')
            }
          }
        },
        createDate: {
          title: '创建时间',
          type: 'text',
          column: {
            formatter({ row }) {
              return dayjs(get(row, 'order.createDate', '-')).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        serverAddrs: {
          title: '服务器地址',
          type: 'text',
          column: {
            formatter({ row }) {
              return (get(row, 'order.server.addresses', []) || []).map((el) => el.addr).join('\n')
            }
          }
        },

        orderStatus: {
          title: '任务执行进度',
          type: 'text',
          column: {
            formatter({ row }) {
              const { status } = row || {}
              const renderPopover = () => {
                let fault = get(row, 'order.server.fault', '')
                try {
                  fault = JSON.parse(fault)
                } catch (e) {}
                return (
                  <a-popover
                    title="错误信息"
                    content={
                      <div class="w-[400px]">
                        <a-descriptions column={3} layout="vertical">
                          <a-descriptions-item label="故障代码">{fault?.code}</a-descriptions-item>
                          <a-descriptions-item label="故障信息">
                            {fault?.message}
                          </a-descriptions-item>
                          <a-descriptions-item label="故障时间">
                            {fault?.created}
                          </a-descriptions-item>
                          <a-descriptions-item label="故障详情" span={3}>
                            {fault?.details}
                          </a-descriptions-item>
                        </a-descriptions>
                      </div>
                    }
                  >
                    <a class="ml-1 !text-red-500">
                      <ExclamationCircleOutlined />
                    </a>
                  </a-popover>
                )
              }
              return (
                <span>
                  {status || '-'}
                  {status === 'FAILURE' ? renderPopover() : null}
                </span>
              )
            }
          }
        },
        serverName: {
          title: '服务器名称',
          type: 'text',
          search: { show: true },
          column: {
            formatter({ row }) {
              return get(row, 'order.server.name', '-')
            }
          }
        },
        projectName: {
          title: '项目',
          type: 'text',
          search: { show: true },
          column: {
            formatter({ row }) {
              return get(row, 'order.server.projectName', '-')
            }
          }
        },
        imageName: {
          title: '镜像名称',
          type: 'text',
          search: { show: true },
          column: {
            formatter({ row }) {
              return get(row, 'order.server.imageName', '-')
            }
          }
        }
      },
      rowHandle: {
        width: 120,
        buttons: {
          view: {
            click({ row }) {
              return router.push({
                path: '/detail',
                query: {
                  id: row.id
                }
              })
            }
          },
          edit: {
            show: false
          },
          remove: {
            show: false
          }
        }
      }
    }
  }
}

const { crudRef, crudBinding, crudExpose } = useFs({ createCrudOptions })

const syncFormRef = ref()
const submitSync = async () => {
  await unref(syncFormRef).validate()
  await http.post('/guanplus/refresh', syncFormData.value)
  syncModalOpen.value = false
  message.success('同步成功')
  crudExpose.doRefresh()
}
// 页面打开后获取列表数据
onMounted(() => {
  crudExpose.doRefresh()
})
</script>

<template>
  <div class="w-10/12 mx-auto py-4 h-[100vh]">
    <a-modal width="400px" v-model:open="syncModalOpen" title="手动同步任务状态" @ok="submitSync">
      <a-alert description="填过一次ak和sk后，会内存里缓存，就可以每5秒自动刷新" show-icon />
      <div class="pt-4">
        <a-form
          ref="syncFormRef"
          :model="syncFormData"
          :rules="{
            ak: [
              {
                required: true,
                message: '请输入ak',
                trigger: 'blur'
              }
            ],
            sk: [
              {
                required: true,
                message: '请输入sk',
                trigger: 'blur'
              }
            ]
          }"
        >
          <a-form-item label="ak" name="ak">
            <a-input v-model:value="syncFormData.ak" allow-clear />
          </a-form-item>
          <a-form-item label="sk" name="sk">
            <a-input v-model:value="syncFormData.sk" allow-clear />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <fs-crud ref="crudRef" v-bind="crudBinding" />
  </div>
</template>

<style scoped lang="less"></style>
